package com.edu.compile.check;

import com.edu.compile.exception.InspectException;
import com.edu.compile.util.LocalNodeEnv;
import com.edu.model.Response;
import com.edu.model.constant.EventConstant;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;
import java.util.List;

public class InspectFunJs implements Inspect {

    private static final Logger LOGGER = LoggerFactory.getLogger(InspectFunJs.class);

    private List<File> files;

    private String eventId;

    public InspectFunJs(List<File> files, String eventId) {
        this.files = files;
        this.eventId = eventId;
    }

    @Override
    public void inspect() {
        if (files == null || files.size() < 1) {
            return;
        }

        if (LocalNodeEnv.hasNode()) {
            StringBuilder sb = new StringBuilder();
            for (File file : files) {
                if (file.getName().startsWith(EventConstant.FUNC_PREFIX + EventConstant.FUNC_NAME_SPLICE_SYMBOL)) {
                    Response response = LocalNodeEnv.hasError(file);
                    if (response.isFail()) {
                        if (sb.length() > 0) {
                            sb.append(" | ");
                        }
                        String message = response.getMsg();
                        try {
                            message = message.replace("\n" + file.getCanonicalPath() + "\n", file.getName());
                        } catch (IOException e) {
                            LOGGER.error("file.getCanonicalPath() call failed: {}", file.getName());
                            continue;
                        }
                        message = message.replace(EventConstant.FUNC_PREFIX + EventConstant.FUNC_NAME_SPLICE_SYMBOL + eventId + EventConstant.FUNC_NAME_SPLICE_SYMBOL, "节点Id：").replace(".js", "");
                        sb.append(message);
                        LOGGER.error("inspect {} failed: {}", file.getName(), message);
                    }
                }
            }
            if (sb.length() > 0) {
                throw new InspectException(sb.toString());
            }
        }
    }
}
